package com.wang.web3;

import android.content.DialogInterface;
import android.os.Environment;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.wang.web3.base.Constant;
import com.wang.web3.bean.TianWallet;
import com.wang.web3.bean.TianWallets;
import com.wang.web3.utils.MyMnemonicUtils;
import com.wang.web3.utils.SPUtils;

import org.bitcoinj.crypto.ChildNumber;
import org.bitcoinj.crypto.DeterministicKey;
import org.bitcoinj.wallet.DeterministicKeyChain;
import org.bitcoinj.wallet.DeterministicSeed;
import org.web3j.crypto.CipherException;
import org.web3j.crypto.ECKeyPair;
import org.web3j.crypto.Keys;
import org.web3j.crypto.WalletUtils;
import org.web3j.utils.Numeric;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static org.bitcoinj.crypto.HDUtils.parsePath;

public class CreateWalletActivity extends AppCompatActivity implements View.OnClickListener{

    EditText etName, etPwd1, etPwd2, etHint;
    //    ProgressLoading progressLoading;
    ImageView imageView;
    String words;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_wallet);
        etName = findViewById(R.id.walletName);
        etPwd1 = findViewById(R.id.walletPwd1);
        etPwd2 = findViewById(R.id.walletPwd2);
        etHint = findViewById(R.id.walletPwdHint);
        imageView = findViewById(R.id.mLeftIv);
        imageView.setOnClickListener(this);
    }

    public void creatWallet(View view){
        String name = etName.getText().toString();
        String pwd1 = etPwd1.getText().toString();
        String pwd2 = etPwd2.getText().toString();
        if (name.equals("") || pwd1.equals("") || pwd2.equals("")){
            Toast.makeText(this,"以上必填信息未填",Toast.LENGTH_SHORT).show();
            return;
        }
        if (!pwd1.equals(pwd2)){
            Toast.makeText(this,"两次密码不一样",Toast.LENGTH_SHORT).show();
            return;
        }


        words = makeMnemonic();
//        tvWords.setText(ss);
        TianWallet tianWallet = createETHWalletFromWords(words);

        Toast.makeText(this,"钱包创建成功",Toast.LENGTH_SHORT).show();



    }

    //生成助记词
    private String  makeMnemonic(){
        byte[] initialEntropy = new byte[16];
        SecureRandom secureRandom = new SecureRandom();
        secureRandom.nextBytes(initialEntropy);
        return MyMnemonicUtils.generateMnemonic(initialEntropy);
    }

    private TianWallet createETHWalletFromWords(String words){
        List<String> list =  Arrays.asList(words.split("\\s+"));
        DeterministicSeed deterministicSeed = new DeterministicSeed(list, null, "", 0);
//        val wordsList = Arrays.asList(*words.split("\\s+".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray())
        DeterministicKeyChain deterministicKeyChain = DeterministicKeyChain.builder().seed(deterministicSeed).build();
        String DERIVATION_PATH = "M/44H/60H/0H/0/0";
        DeterministicKey deterministicKey = deterministicKeyChain.getKeyByPath(parsePath(DERIVATION_PATH), true);

        BigInteger privateKey = deterministicKey.getPrivKey();

        ECKeyPair ecKeyPair = ECKeyPair.create(privateKey);


        try {
            String filePath = Environment.getExternalStorageDirectory().getAbsolutePath().toString() + Constant.WalletUri;
            String fileName =  WalletUtils.generateWalletFile(etPwd1.getText().toString(),ecKeyPair,new File(filePath),false);

            FileInputStream inputStream = new FileInputStream(filePath + "/" + fileName);
            byte temp[] = new byte[1024];
            StringBuilder sb = new StringBuilder("");
            int len = 0;
            while ((len = inputStream.read(temp)) > 0){
                sb.append(new String(temp, 0, len));
            }
            String string = sb.toString();
            Log.e("tag","------" + ecKeyPair.toString());
        } catch (CipherException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String address = Keys.getAddress(ecKeyPair);

//        progressLoading.hideLoading();
        TianWallet tianWallet = new TianWallet(etName.getText().toString(), "0x" + address, Numeric.toHexStringWithPrefix(ecKeyPair.getPrivateKey()), Numeric.toHexStringWithPrefix(ecKeyPair.getPublicKey()), words);

        Gson gson = new Gson();
        //读出原有的
        String ss = (String) SPUtils.get(this,Constant.WalletKey,"");
        TianWallets wallets;
        if (!ss.equals("")){
            wallets = gson.fromJson(ss, TianWallets.class);
        }else {
            wallets = new TianWallets(new ArrayList<TianWallet>());
        }

        wallets.getTianWallets().add(tianWallet);

        SPUtils.put(this,Constant.WalletKey,gson.toJson(wallets));

        AlertDialog alertDialog = new AlertDialog.Builder(this).create();
        alertDialog.setTitle("助记词");
        alertDialog.setMessage("" + words + "\n *****请务必亲自备份");
        alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "确定且已经备份", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                finish();
            }
        });
        alertDialog.setCanceledOnTouchOutside(false);
        alertDialog.show();


        return tianWallet;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.mLeftIv:
                finish();
                break;
        }
    }
}
